Server-Sent Events (SSE) is a mechanism that allows a server to push real-time updates to a client over a single HTTP connection. SSE is based on the HTTP protocol and allows the server to send automatic updates to the browser without the client needing to repeatedly request new data (unlike polling).
EventSource
.res.write()
in the format:
onmessage
handler.eventSource.close()
.✅ Simple to implement since it uses standard HTTP.
✅ Efficient compared to long polling since only one connection is maintained.
✅ Automatic reconnection on connection loss.
✅ Can send custom event types.
❌ Only supports unidirectional communication (server → client).
❌ Works only over HTTP/HTTPS (not WebSockets).
❌ Limited by the maximum number of concurrent HTTP connections per browser (around 6).
You can also define custom event types like this:
Server:
Client:
To receive SSE notifications, you create an instance of the EventSource
class, which establishes a persistent connection to a server that sends events. Here's an example:
The server sends events in a specific format like this:
You can check if the browser supports SSE using the following code:
The following events are available for EventSource
:
Event | Description |
---|---|
open | Fired when the connection to the server is established. |
message | Fired when a message is received from the server. |
error | Fired when an error occurs or the connection closes unexpectedly. |
You can also define custom event types on the server side by prefixing the event name with event:
:
In JavaScript:
This allows you to define and handle specific types of events beyond the standard message
, open
, and error
events.